<?php

namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Db;

class Agent extends Controller
{
    /**
     * 定时任务,到期代理时间结束
     */
    public function crontabAgent()
    {
        $crontab_data = Db::table('ad_user_agent_crontab')->where('end_time', '<=',
            time())->where(['deleted_at' => 0])->select();
        if (!empty($crontab_data)) {
            Db::transaction(function () use ($crontab_data) {
                foreach ($crontab_data as $item => $value) {
                    Db::table('ad_user_info')->where(['uid' => $value['uid']])->update(['is_open' => 2]);
                    Db::table('ad_user_agent')->where(['uid' => $value['uid']])->update(['status' => 0]);
                    Db::table('ad_user_agent_crontab')->where(['id' => $value['id']])->update(['deleted_at' => 1]);
                }
            });
        }
        return json('success');
    }


    /**
     * @return \think\response\Json
     * 查询充值订单
     */
    public function check_withdraw()
    {
        $allWithDrawOrder = Db::name('finance')->where([
            'progress' => 3,
            'withdraw_status' => 0,
            'status' => 3,
            'withdraw_status' => 0,
        ])->field(['trade_no', 'id', 'uid', 'coin', 'withdraw_money'])->select();
        $output_data = [];
        foreach ($allWithDrawOrder as $item => $value) {
            // 公共配置
            $params           = new \Yurun\PaySDK\Weixin\Params\PublicParams;
            $params->appID    = 'wxd38af918cc55bb7c';
            $params->mch_id   = '1410856402';
            $params->key      = 'heilongjiangQingqiyunxiehehai001';
            $params->certPath = ROOT_PATH . 'public/cert_withdraw/apiclient_cert.pem';
            $params->keyPath  = ROOT_PATH . 'public/cert_withdraw/apiclient_key.pem';

            // SDK实例化，传入公共配置
            $sdk                       = new \Yurun\PaySDK\Weixin\SDK($params);
            $request                   = new \Yurun\PaySDK\Weixin\CompanyPay\Bank\Query\Request;
            $request->partner_trade_no = $value['trade_no']; // 订单号
            $result                    = $sdk->execute($request);
            $verify_result             = $sdk->checkResult();


            if (!empty($result['status']) && $result['status'] == 'SUCCESS' && $verify_result) {
                //更新提现状态
                Db::table('ad_finance')->where(['id' => $value['id']])->update([
                    'withdraw_status' => 1,
                    'bank_payment_no' => $result['payment_no'],
                    'apply_time' => time()
                ]);
                //推送数据
                $data_send = [
                    'user_name' => Db::name('user_info')->where(['uid' => $value['uid']])->value('phone'),
                    'rmb' => $value['withdraw_money'],
                    'lcb' => $value['coin']
                ];
                $this->sendMessage($data_send);
            }
            $output_data[] = $result;
        }
        return json(['code' => 200, 'info' => '已获取到数据', 'data' => $output_data]);
    }

    /**
     * @param array $post_data
     * @return mixed
     * 发送消息
     */
    public function sendMessage($post_data = [])
    {
        $url = "http://api.lchyh.com/api/User/ldata_add_tx";
        $ch  = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);
        //打印获得的数据
        //延时处理下(防止阻塞)
        usleep(2000000);
        return $output;
    }


    /**
     * @return bool
     * array:6 [▼
        "return_code" => "SUCCESS"
        "return_msg" => "参数错误,请检查参数"
        "result_code" => "FAIL"
        "err_code" => "PARAM_ERROR"
        "err_code_des" => "持卡人姓名有误，请检查"
        "mch_id" => "1410856402"
        ]
     */
    public function testWithdraw()
    {
        $params           = new \Yurun\PaySDK\Weixin\Params\PublicParams;
        $params->appID    = 'wxd38af918cc55bb7c';
        $params->mch_id   = '1410856402';
        $params->key      = 'heilongjiangQingqiyunxiehehai001';
        $params->certPath = ROOT_PATH . 'public/cert_withdraw\apiclient_cert.pem';
        $params->keyPath  = ROOT_PATH . 'public/cert_withdraw\apiclient_key.pem';


        // SDK实例化，传入公共配置
        $sdk                        = new \Yurun\PaySDK\Weixin\SDK($params);
        $request                    = new \Yurun\PaySDK\Weixin\CompanyPay\Bank\Pay\Request;
        $request->rsaPublicCertFile = ROOT_PATH . 'public/cert_withdraw\public-1410856402.pem'; // 设置证书路径，用于加密银行卡号、姓名、开户行
        $request->partner_trade_no  = '112018051519698'; // 订单号
        $request->enc_bank_no       = '6214838772067197';//银行卡号
        $request->enc_true_name     = '谢何海';//银行卡对应的真实姓名
        $request->bank_code         = '1003';//银行编码
        $request->amount            = 1001;
        $request->desc              = 'HYH区块链广告平台提现';
        $result                     = $sdk->execute($request);
        $verify_result              = $sdk->checkResult();
        dd($result);
        if ($result['return_code'] == 'SUCCESS' && $verify_result) {
            return true;
        }

    }


}